package juc.lock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author fangbin
 * @desc 演示锁的升降级
 * @date 2020/6/12 19:04
 */
public class Upgrading {

    public static ReentrantReadWriteLock reentrantReadWriteLock =
            new ReentrantReadWriteLock(false);

    public static ReentrantReadWriteLock.ReadLock readLock =
            reentrantReadWriteLock.readLock();
    public static ReentrantReadWriteLock.WriteLock writeLock =
            reentrantReadWriteLock.writeLock();

    public static  void readUp(){
        System.out.println(Thread.currentThread().getName()+"尝试获取读锁");
        try{
            readLock.lock();
            System.out.println(Thread.currentThread().getName()+"得到锁，正在读取");
            Thread.sleep(20);
            System.out.println("升级会带来阻塞");
            writeLock.lock();
            System.out.println("升级成功"+Thread.currentThread().getName()+"获取到了写锁");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println(Thread.currentThread().getName()+"释放读锁");
            readLock.unlock();
        }
    }
    public static  void writeDown(){
        System.out.println(Thread.currentThread().getName()+"尝试获取写锁");
        try{

            writeLock.lock();
            System.out.println(Thread.currentThread().getName()+"得到锁，正在写入");
            Thread.sleep(40);
            System.out.println("开始降级，获得读锁");
            System.out.println("降级成功"+Thread.currentThread().getName()+"获取到了读锁");
            readLock.lock();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            readLock.unlock();
            System.out.println(Thread.currentThread().getName()+"释放写锁");
            writeLock.unlock();
        }
    }

    public static void main(String[] args) {

        //锁降级
        new Thread(()->readUp()).start();
        //锁升级
        new Thread(()->writeDown()).start();

    }
}
